package com.itheima.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.itheima.dto.AdminDto;
import com.itheima.mapper.AdminMapper;
import com.itheima.po.Admin;
import com.itheima.service.AdminService;
import com.itheima.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author :wujunjie
 * createTime :2023-01-03 20:54
 * description :
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public AdminVo login(AdminDto adminDto) {
        MPJLambdaWrapper<Admin> selectWrapper=new MPJLambdaWrapper<>();
        selectWrapper.eq(Admin::getName, adminDto.getName());
        selectWrapper.eq(Admin::getPassword, adminDto.getPassword());
        Admin adminInDB = adminMapper.selectOne(selectWrapper);
        if (ObjectUtils.isEmpty(adminInDB)){
            throw new RuntimeException("账号或密码错误");
        }
        AdminVo adminVo = new AdminVo();
        adminInDB.setPassword(null);
        adminVo.setUser(adminInDB);
        adminVo.setToken(getToken(adminInDB.getId()));
        return adminVo;
    }

    private static String getToken(String id) {
        DateTime now = DateUtil.date();
        DateTime exp = DateUtil.offset(now, DateField.HOUR, 24);
        Map<String,Object> payload=new HashMap<>();
        payload.put(RegisteredPayload.ISSUED_AT,now);
        payload.put(RegisteredPayload.NOT_BEFORE, now);
        payload.put(RegisteredPayload.EXPIRES_AT,exp);
        payload.put("id",id);
        return JWTUtil.createToken(payload, "heimaLeadnews".getBytes());
    }
}
